// 导入数据库
const db = require("../db/index");
const ut = require("../utils/utils");

// 获取分类信息
exports.getCates = (req, res) => {
    const sql = `select * from ev_article_cate where is_delete=0 order by id asc`;
    db.query(sql, (err, results) => {
        if (err) return res.mess(err);
        return res.send({
            status: 200,
            message: "获取分类成功！",
            data: results,
        });
    });
};

// 添加分类
exports.addCates = (req, res) => {
    const data = req.body;
    ut.isNotUsed(req, res).then(() => {
        // 添加新的分类
        const addCates = `insert into ev_article_cate set ?`;
        db.query(addCates, data, (err, results) => {
            if (err) return res.mess(err);
            if (results.affectedRows !== 1) return res.mess("添加分类失败！");
            return res.mess("添加分类成功！", 200);
        });
    });
};

// 根据id删除分类
exports.deleteCateById = (req, res) => {
    const deleteCate = `update ev_article_cate set is_delete=1 where id=?`;
    db.query(deleteCate, req.params.id, (err, results) => {
        if (err) return res.mess(err);
        if (results.affectedRows !== 1) return res.mess("删除失败!");
        return res.mess("删除成功！", 200);
    });
};

// 根据id获取文章分类
exports.getCateById = (req, res) => {
    const selectCate = "select * from ev_article_cate where id=?";
    db.query(selectCate, req.params.id, (err, results) => {
        if (err) return res.mess(err);
        if (results.length !== 1) return res.mess("获取失败!");
        return res.send({
            status: 200,
            message: "获取成功！",
            data: results[0],
        });
    });
};

// 根据id修改文章分类
exports.updateCate = (req, res) => {
    const data = req.body;
    ut.isNotUsed(req, res).then(() => {
        const updateCate = `update ev_article_cate set ? where id=?`;
        db.query(
            updateCate, [{ name: data.name, alias: data.alias }, data.id],
            (err, results) => {
                if (err) return res.mess(err);
                if (results.affectedRows !== 1) return res.mess("修改分类信息失败!");
                return res.mess("修改分类信息成功！", 200);
            }
        );
    });
};